/*
    加入购物车的书籍
 */
let booksCart = [];
let cart = null;
let ind = -1;

function getCartBooks() {
    let result = [];
    let formData = new FormData();
    formData.append("relation","CART");
    $.ajax({
        type: "post",
        url: "/api/relationBook/u/getRelationBookByUserRelation",
        dataType: "text",
        async: false,
        data: formData,
        processData: false,
        contentType: false,
        success: data => {
            data = eval('(' + data + ')');
            if (data.success) {
                result = JSON.parse(data.data);
            } else {
                alert(data.msg);
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            const msg = xhr.responseText;
            console.log(msg);
        }
    });
    return result;
}

function updateCart() {
    $.ajax({
        type: "post",
        url: "/api/userBookRelation/u/modifyRelation",
        dataType: "text",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify({
            "storeId": cart.storeId,
            "bookIsbn": cart.bookIsbn,
            "relation": cart.relation,
            "num": cart.num
        }),
        success: data => {
            data = eval('('+ data +')');
            if (data.success) {
                return true;
            }else {
                alert(data.msg);
                return false;
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            const msg = xhr.responseText;
            console.log(msg);
        }
    })
    return false;
}

function deleteCart() {
    $.ajax({
        type: "post",
        url: "/api/userBookRelation/u/deleteRelation",
        dataType: "text",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify({
            "storeId": cart.storeId,
            "bookIsbn": cart.bookIsbn,
            "relation": cart.relation,
            "num": cart.num
        }),
        success: data => {
            data = eval('('+ data +')');
            if (data.success) {
                return true;
            }else {
                alert(data.msg);
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            const msg = xhr.responseText;
            console.log(msg);
        }
    });
    return false;
}

function updateEvent() {
    let updateItem = $("table.table>tbody tr").eq(ind);
    cart = booksCart[ind];
    cart.num = $(updateItem).find("div.cart-plus-minus>input.cart-plus-minus-box").val();
    if (cart.num>cart.number) {
        alert("库存不够");
        $(updateItem).find("div.cart-plus-minus>input.cart-plus-minus-box").val(booksCart[ind].num);
    }else {
        if (updateCart()) {
            $(updateItem).find("td.product-subtotal>span.amount").text(toDecimal(cart.price*cart.num));
            booksCart[ind] = cart;
        }else {
            $(updateItem).find("div.cart-plus-minus>input.cart-plus-minus-box").val(booksCart[ind].num);
            alert("修改数量失败");
        }
    }
    cart = null;
    ind = -1;
}

function deleteEvent() {
    let updateItem = $("table.table>tbody tr").eq(ind);
    cart = booksCart[ind];
    if (deleteCart()) {
        $(updateItem).remove();
        booksCart = getCartBooks();
    }
    cart = null;
    ind = -1;
}

function getCartBookTemplate(cartBook, ind) {
    return "<tr ind='"+ ind +"'>" +
        "<td class='umino-product-remove'>" +
        "<a href='javascript:void(0)'><i class='fa fa-trash' title='Remove'></i></a>" +
        "</td>" +
        "<td class='umino-product-thumbnail'>" +
        "<a href='javascript:void(0)'><img src='..//..//images//" + cartBook.img + "' alt=''></a>" +
        "</td>" +
        "<td class='umino-product-name'><a href='javascript:void(0)'>" + cartBook.bookName + "</a></td>" +
        "<td class='umino-product-price'><span class='amount'>" + cartBook.price + "</span></td>" +
        "<td class='quantity'>" +
        "<label>购买数量</label>" +
        "<div class='cart-plus-minus'>" +
        "<input class='cart-plus-minus-box' value='"+ cartBook.num +"' type='text'>" +
        "<div class='dec qtybutton'><i class='fa fa-angle-down'></i></div>" +
        "<div class='inc qtybutton'><i class='fa fa-angle-up'></i></div>" +
        "</div>" +
        "</td>" +
        "<td class='product-subtotal'><span class='amount'>"+ toDecimal(cartBook.price*cartBook.num) +"</span></td>" +
        "</tr>";
}

function toDecimal(x) {
    let f = parseFloat(x);
    if (isNaN(f)) {
        return;
    }
    f = Math.round(x*100)/100;
    return f;
}

function initDOM() {
    let table = $("table.table>tbody");
    booksCart.forEach((cartBooks, ind) => {
        let template = getCartBookTemplate(cartBooks, ind);
        $(table).append(template);
    })
    $(table).find("td.umino-product-remove>a").on("click", function() {
        //todo: [2021-4-13]获取点击对象的ind
    })
}

$(document).ready(function() {
    booksCart = getCartBooks();
    if (booksCart.length>0) {

    }
})